package com.ashin.context;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 *  获取和设置上下文租户id
 */
public class TenantIdContext {

    public static final String TENANTCODE_ATTRIBUTE = "TENANTCODE_ATTRIBUTE";


    public static String getTenantCodeThreadLocal() {
        return (String) RequestContextHolder.getRequestAttributes().getAttribute(TENANTCODE_ATTRIBUTE, 0);
    }

    public static void setTenantCodeThreadLocal(String tenantCode) {
        if (RequestContextHolder.getRequestAttributes() != null) {
            RequestContextHolder.getRequestAttributes().setAttribute(TENANTCODE_ATTRIBUTE, tenantCode, 0);

        } else {
            ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(new DefaultHttpServletRequest());
            RequestContextHolder.setRequestAttributes(servletRequestAttributes);
            servletRequestAttributes.setAttribute(TENANTCODE_ATTRIBUTE, tenantCode, 0);
        }
    }

    public static void removeTenantCodeThreadLocal() {
        if (RequestContextHolder.getRequestAttributes() != null) {
            RequestContextHolder.getRequestAttributes().removeAttribute(TENANTCODE_ATTRIBUTE, 0);
        }

    }
}
